package com.naruto.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.SimpleFormatter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.naruto.dao.BaseMapper;
import com.naruto.dao.MemberMapper;
import com.naruto.entity.MemberEntity;
import com.naruto.response.BaseResponse;

@Service
public class MemberService {

	@Autowired
	BaseMapper basicMapper;
	@Autowired
	MemberMapper schoolMapper;
	// 三表联查 会员&会员等级&会员积分
	@Transactional
	public String getMember(int pageNow) {
//		String sql_select = "SELECT * FROM `member` a,`rank` r,`points` p,`recharge` re where a.rank_id = r.id and a.id = p.member_id and re.member_id = a.id";
		String sql_select = "SELECT a.*,p.totalpoits,p.usedpoits,re.rechargeAmount FROM member a,points p,recharge re where a.id = p.member_id and re.member_id = a.id group by a.id";

		String sql_rank ="select id as rank_id,rankcount,rankName,starttime,endtime from rank order by rankcount asc";
		Map<String, Object> paramMap2 = new HashMap<String, Object>();
		paramMap2.put(BaseMapper.SQLFIELD, sql_rank);
		List<Map<String, Object>> ranks = basicMapper.fetch(paramMap2);
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put(BaseMapper.SQLFIELD, sql_select);

		PageHelper.startPage(pageNow, 5);// 从第一页开始，每页2条数据
		Page<Map<String, Object>> pageResult = basicMapper.fetchPage(paramMap);
		
		for(int i=0;i<pageResult.size();i++)
		{
			Map<String, Object> map =pageResult.get(i);
			
			Double total = Double.parseDouble(map.get("totalpoits")+"");
			Double used =Double.parseDouble(map.get("usedpoits")+"");
			String birthday =(map.get("birthday")+"");
			String registerTime =(map.get("registerTime")+"");
			map.put("birthday", birthday);
			map.put("registerTime", registerTime);
			//取最大积分  第一次total >used 累计使用后used>total
			Map<String, Object> rankmap ;
			if(total>used) 
			{
				rankmap = sort(ranks,total);
			}else 
			{
				rankmap = sort(ranks,used);
			}
			if(rankmap!=null) 
			{
				map.putAll(rankmap);
			}
			pageResult.set(i, map);
		}
		
		PageInfo<Map<String, Object>> p = new PageInfo<>(pageResult);

		String json = JSON.toJSONString(p);
		return json;
	}
	
	private Map<String, Object> sort(List<Map<String, Object>> ranks, Double points) {
		// TODO Auto-generated method stub
		for(int i=0;i<ranks.size();i++)
		{
			Map<String,Object> map = ranks.get(i);
			Double  temp =Double.parseDouble(map.get("rankcount")+"");
			//升序
			if(temp >=points) 
			{
				return map;
			}
		}		
		return  ranks.size()>0?ranks.get(0):null;
	}

	@Transactional
	public String getMemberById(int pageNow,String id) {
		String sql_select = "SELECT a.*,p.totalpoits,p.usedpoits,re.rechargeAmount FROM `member` a,`points` p,`recharge` re where a.id = p.member_id and re.member_id = a.id and (a.id like #{id} or a.telephone like #{id}) group by a.id";
		
		String sql_rank ="select id as rank_id,rankcount,rankName,starttime,endtime from rank order by rankcount asc";
		Map<String, Object> paramMap2 = new HashMap<String, Object>();
		paramMap2.put(BaseMapper.SQLFIELD, sql_rank);
		List<Map<String, Object>> ranks = basicMapper.fetch(paramMap2);
		
		
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put(BaseMapper.SQLFIELD, sql_select);
		paramMap.put("id", id);
		PageHelper.startPage(pageNow, 5);// 从第一页开始，每页2条数据
		Page<Map<String, Object>> pageResult = basicMapper.fetchPage(paramMap);
		for(int i=0;i<pageResult.size();i++)
		{
			Map<String, Object> map =pageResult.get(i);
			
			Double total = Double.parseDouble(map.get("totalpoits")+"");
			Double used =Double.parseDouble(map.get("usedpoits")+"");
			//取最大积分  第一次total >used 累计使用后used>total
			Map<String, Object> rankmap ;
			if(total>used) 
			{
				rankmap = sort(ranks,total);
			}else 
			{
				rankmap = sort(ranks,used);
			}
			if(rankmap!=null) 
			{
				map.putAll(rankmap);
			}
			pageResult.set(i, map);
		}
		PageInfo<Map<String, Object>> p = new PageInfo<>(pageResult);
		
		String json = JSON.toJSONString(p);
		return json;
	}

	// 三表联查 会员&会员等级&会员积分
	@Transactional
	public String getMemberDetail(int memberId) {
		String sql_select = "SELECT a.*,p.totalpoits,p.usedpoits,re.rechargeAmount FROM `member` a,`points` p,`recharge` re where a.id = p.member_id and re.member_id = a.id and a.id=#{id} group by a.id";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put(BaseMapper.SQLFIELD, sql_select);
		paramMap.put("id", memberId);

		String sql_rank ="select id as rank_id,rankcount,rankName,starttime,endtime from rank order by rankcount asc";
		Map<String, Object> paramMap2 = new HashMap<String, Object>();
		paramMap2.put(BaseMapper.SQLFIELD, sql_rank);
		List<Map<String, Object>> ranks = basicMapper.fetch(paramMap2);
		
		List<Map<String, Object>> pageResult = basicMapper.fetch(paramMap);
		if (pageResult != null && pageResult.size() > 0) {
			
			for(int i=0;i<pageResult.size();i++)
			{
				Map<String, Object> map =pageResult.get(i);
				
				Double total = Double.parseDouble(map.get("totalpoits")+"");
				Double used =Double.parseDouble(map.get("usedpoits")+"");
				//取最大积分  第一次total >used 累计使用后used>total
				Map<String, Object> rankmap ;
				if(total>used) 
				{
					rankmap = sort(ranks,total);
				}else 
				{
					rankmap = sort(ranks,used);
				}
				if(rankmap!=null) 
				{
					map.putAll(rankmap);
				}
				pageResult.set(i, map);
			}
			
			String json = JSON.toJSONString(pageResult.get(0));
			return json;
		} else {
			BaseResponse adminLoginResp = new BaseResponse();
			adminLoginResp.setStatus("-1");
			adminLoginResp.setResultMsg("会员信息不存在！");
			String json = JSON.toJSONString(adminLoginResp);
			return json;
		}

	}
	@Transactional
	public String checkUser(MemberEntity memberEntity) 
	{
		String sql_select = "select * from member where username= #{username}";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put(BaseMapper.SQLFIELD, sql_select);
		paramMap.put("username", memberEntity.getUsername());
		List<Map<String, Object>> list = basicMapper.fetch(paramMap);
		if (list != null && list.size() > 0) {
			BaseResponse adminLoginResp = new BaseResponse();
			adminLoginResp.setStatus("-1");
			adminLoginResp.setResultMsg("会员账号已存在");
			String json = JSON.toJSONString(adminLoginResp);
			return json;
		}else 
		{
			BaseResponse adminLoginResp = new BaseResponse();
			adminLoginResp.setStatus("0");
			adminLoginResp.setResultMsg("会员账号可以使用");
			String json = JSON.toJSONString(adminLoginResp);
			return json;
		}
	}

	public String createMember(MemberEntity memberEntity) {
		// 创建会员记录 默认添加会员积分记录和会员等级
		// 查询是否存在
		// 创建
		// 初始化两条记录
		String sql_select = "select * from member where username= #{username}";
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put(BaseMapper.SQLFIELD, sql_select);
		paramMap.put("username", memberEntity.getUsername());
		List<Map<String, Object>> list = basicMapper.fetch(paramMap);
		if (list == null || list.size() == 0) {
			System.out.println(memberEntity.toString());
			// 创建会员 同是初始化 积分和等级
			String sql_add = "INSERT INTO `academy`.`member`"
					+ " ( `name`, `telephone`, `sex`, `school`, `birthday`, `email`, `major`, `number`, `address`, `performance`, `password`, `username`, `openid`, `weixinno`, `weixinimg`)"
					+ " VALUES "
					+ "(#{name}, #{telephone}, #{sex}, #{school}, #{birthday}, #{email}, #{major}, #{number}, #{address}, #{performance}, #{password}, #{username}, #{openid}, #{weixinno}, #{weixinimg});";

			Map<String, Object> paramMap2 = new HashMap<String, Object>();
			paramMap2.put(BaseMapper.SQLFIELD, sql_add);
			paramMap2.put("name", memberEntity.getName());
			paramMap2.put("telephone", memberEntity.getTelephone());
			paramMap2.put("sex", memberEntity.getSex());
			paramMap2.put("school", memberEntity.getSchool());
			paramMap2.put("birthday", memberEntity.getBirthday());
			paramMap2.put("email", memberEntity.getEmail());
			paramMap2.put("major", memberEntity.getMajor());
			paramMap2.put("address", memberEntity.getAddress());
			paramMap2.put("performance", memberEntity.getPerformance());
			paramMap2.put("password", memberEntity.getPassword());
			paramMap2.put("username", memberEntity.getUsername());
			paramMap2.put("openid", memberEntity.getOpenid()+"");
			paramMap2.put("weixinno", memberEntity.getWeixinno()+"");
			paramMap2.put("weixinimg", memberEntity.getWeixinimg()+"");
//
//
			int res = basicMapper.executeUpdate(paramMap2);
//			int res =schoolMapper.insertSelective(memberEntity);
			String sql_select2 = "SELECT MAX(id) FROM member";
			Map<String, Object> paramMaps = new HashMap<String, Object>();
			paramMaps.put(BaseMapper.SQLFIELD, sql_select2);
			long ids = basicMapper.executeLong(paramMaps);
			System.out.println("res :"+ids);
			if (res > 0) {

				String sql_add2 = "INSERT INTO `academy`.`points` (`member_id`, `cardNo`) VALUES (#{member_id}, #{cardNo}); ";
				Map<String, Object> paramMap3 = new HashMap<String, Object>();
				paramMap3.put(BaseMapper.SQLFIELD, sql_add2);
				paramMap3.put("member_id", ids);
				paramMap3.put("cardNo", ids);
				int res3 = basicMapper.executeUpdate(paramMap3);
				
				String sql_add3 = "INSERT INTO `academy`.`recharge` (`member_id`) VALUES (#{member_id}); ";
				Map<String, Object> paramMap4 = new HashMap<String, Object>();
				paramMap4.put(BaseMapper.SQLFIELD, sql_add3);
				paramMap4.put("member_id", ids);
				int res2 = basicMapper.executeUpdate(paramMap4);

				BaseResponse adminLoginResp = new BaseResponse();
				adminLoginResp.setStatus("0");
				adminLoginResp.setResultMsg("创建成功");
				String json = JSON.toJSONString(adminLoginResp);
				return json;
			} else {
				BaseResponse adminLoginResp = new BaseResponse();
				adminLoginResp.setStatus("-1");
				adminLoginResp.setResultMsg("保存失败");
				String json = JSON.toJSONString(adminLoginResp);
				return json;
			}
		} else {
			BaseResponse adminLoginResp = new BaseResponse();
			adminLoginResp.setStatus("-1");
			adminLoginResp.setResultMsg("会员账号已存在");
			String json = JSON.toJSONString(adminLoginResp);
			return json;
		}
	}
}
